/*
 *  Copyright 2008 Mark Ashworth <javameme@gmail.com>.
 * 
 *  Licensed under the GNU General Public License v3 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.gnu.org/licenses/gpl-3.0.html
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package xperiment.metaphor.persistence.user.hibernate;

import xperiment.metaphor.persistence.user.RoleAlreadyExistsDaoException;
import xperiment.metaphor.persistence.hibernate.*;
import java.io.Serializable;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Expression;
import org.springframework.dao.DataAccessException;
import org.springframework.transaction.annotation.Transactional;
import xperiment.metaphor.model.user.Role;
import xperiment.metaphor.model.user.User;
import xperiment.metaphor.persistence.DaoException;
import xperiment.metaphor.persistence.user.RoleDao;

/**
 * Hibernate Role Data Access Object
 * @author Mark Ashworth <javameme@gmail.com>
 * @version 1.0.0
 */
public class HibernateRoleDao extends HibernateDao<Role> implements RoleDao {

    /**
     * Default constructor
     */
    public HibernateRoleDao() {
        super(User.class);
    }
	
    /**
     * Retrieves the role by name using a case-insensitive lookup.
     * @param name The name of the role
     * @return Role or null if the role could not be found
     * @throws DataAccessException If there was an persistence error
     */
    @Override
    @Transactional(readOnly=true)
	public Role retrieveByName(String name) {
		
		Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(User.class);
		criteria.add(Expression.ilike("name", name));
		return (Role) criteria.uniqueResult();
	}
    
    /**
     * Persists the role. <br />
     * 
     * If the role.id is null and the role name already exists
     * in the database then it is assumed that the intention is to edit the
     * role in the database with the new values in the role.<br />
     * 
     * If the role.id does not match the role.id of a role entry with the same
     * name then a RoleAlreadyExistsDaoException is raised stating that the role already
     * exists.
     * 
     * @param role The role to persist
     * @return The persisted role
     * @throws DaoException If there was an error
     * @throws IllegalArgumentException If the role or name is null
     * @throws DataAccessException If there was an error persisting or loading the role from the database
     * @throws RoleAlreadyExistsDaoException If the username would cause a duplicate role name
     */
    @Override
    @Transactional
	public Role persist(Role role) throws RoleAlreadyExistsDaoException {
        if (role == null) {
            throw new IllegalArgumentException("The role is null");
        } else if (role.getName() == null) {
            throw new IllegalArgumentException("The role name is null");
        }
        
        Role temp = retrieveByName(role.getName());
        if (role.getId() == null && temp != null) {
            role.setId(temp.getId());
        } else if (temp != null && temp.getId() != null && !role.getId().equals(temp.getId())) {
            throw new RoleAlreadyExistsDaoException("The role name is already taken");
        }
        
        Serializable id = getHibernateTemplate().save(role);
        return (Role) getHibernateTemplate().load(Role.class, id);
	}
}
